package com.situ.mall.admin.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.situ.mall.common.util.CommonUtil;
import com.situ.mall.common.util.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/admin")
public class CaptchaController {
    //private Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("CaptchaController.captcha");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String captcha = defaultKaptcha.createText();
        log.info("验证码：{}", captcha);
        //验证码存储到redis中  设置失效时间10分钟
        redisTemplate.opsForValue().set(CommonUtil.getCaptchaKey(request), captcha, 60 * 1000, TimeUnit.MILLISECONDS);

        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(captcha);
        //ServletOutputStream out = response.getOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", out);
        String base64Code = Base64.encodeBase64String(out.toByteArray());

        return Result.ok("", "data:image/png;base64," + base64Code);
    }


    @GetMapping("/captcha1")
    public void captcha1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("CaptchaController.captcha");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String captcha = defaultKaptcha.createText();
        log.info("验证码：{}", captcha);
        //验证码存储到redis中  设置失效时间10分钟
        redisTemplate.opsForValue().set(CommonUtil.getCaptchaKey(request), captcha, 10 * 60 * 1000, TimeUnit.MILLISECONDS);

        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(captcha);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();

    }


}
